package com.hmy.cornpestdet.service;

import com.hmy.cornpestdet.mapper.AdminInitMapper;
import com.hmy.cornpestdet.pojo.MyPoint;
import com.hmy.cornpestdet.utils.CPDConst;
import com.hmy.cornpestdet.utils.PositionUtil;
import com.hmy.cornpestdet.utils.Result;
import com.hmy.cornpestdet.vo.AutoWarningSystem;
import com.hmy.cornpestdet.vo.AutoWarningSystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminInitService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AdminInitMapper adminInitMapper;

    public void init() {
        int uid = getUid();
        if(uid == -1)return;
        List<AutoWarningSystemUser> list = getAllUserInfo();
        //获得当前用户的水稻患病率
        double diseaseRate = adminInitMapper.getDiseaseRateByUid(uid);
        //如果当前用户的患病率超过30%就向周围100km范围用户发布预警提醒
        if(diseaseRate > 30.0){
            sendWarningToUser(uid, list,100.0);
        }
    }
    //向周围范围内用户发布预警信息(km)
    private void sendWarningToUser(int uid, List<AutoWarningSystemUser> list, double distance){
        //拿到当前用户的uid
        MyPoint mPosition = null;
        for(AutoWarningSystemUser user : list){
            if(user.getUid() == uid){
                mPosition = user.getPosition();
            }
        }
        //范围内用户都发布预警信息
        if(mPosition != null){
            for(AutoWarningSystemUser user : list){
                if(user.getPosition() != null &&  PositionUtil.getDistance1(mPosition, user.getPosition()) < distance){
                    send(user.getUid(),uid,PositionUtil.getDistance1(mPosition, user.getPosition()) );
                }
            }
        }
    }


    //获取当前用户的uid
    private int getUid(){
        String uidStr = redisTemplate.opsForValue().get(CPDConst.CURRENT_USER_UID);
        if(uidStr == null){
            return -1;
        }
        int uid = Integer.valueOf(uidStr);
        return uid;
    }
    //获得所有用户的uid和坐标信息
    private List<AutoWarningSystemUser> getAllUserInfo(){
        return adminInitMapper.getAllUserInfo();
    }
    //向指定用户发布预警信息(插入到数据库中)
    private void send(int rUid,int sUid,double distance){
        adminInitMapper.send(rUid,sUid,distance);
    }


    //暴露给用户定时查询自动预警信息（传来的uid是接收方uid）
    public Result getAutoWarningInfoByUid() {
        int uid = getUid();
        if(uid == -1)return Result.Error("");

        List<AutoWarningSystem> list = adminInitMapper.getAutoWarningInfo(uid);
        if(list == null){
            return Result.Error("");
        }
        return Result.Success("",list);
    }
}
